#include "exportdatathread.h"

ExportDataThread::ExportDataThread(SensorType type,qint64 startTime,
                                   qint64 endTime,QString path,QObject *parent) :
    QThread(parent)
{
    this->type = type;
    this->startTime = startTime;
    this->endTime = endTime;
    this->path = path;
}

void ExportDataThread::run()
{
    DatabaseHelper helper(NULL,"subThread");
    QList<QString> result = helper.selectData(type,startTime,endTime);
    if(result.size() == 0)
    {
        emit progressSignal(-1); // 非正常结果
        return;
    }
    QFile file(path);
    file.open(QIODevice::WriteOnly);
    QTextStream output(&file);

    // 上一次和本次的百分比
    int lastPer = 0;
    int currentPer = 0;
    int hasWritedCount = 0; // 已经写出的数量

    QListIterator<QString> iter(result);

    output << QString("ID   value   time") << endl;
    output << QString("可直接复制到Excel中进行统计分析") << endl;

    while(iter.hasNext())
    {
        // 拖慢一点
        msleep(10);

        QString record = iter.next();
        output << record << endl;
        hasWritedCount++;
        currentPer = hasWritedCount*100/result.size();
        if(currentPer > lastPer)
        {
            lastPer = currentPer;
            emit progressSignal(currentPer);
        }
    }
    file.flush();
    file.close();
}

